<?php
namespace app\admin\controller;
use app\admin\collection\permissionCollection;
use app\admin\model\Group;
use app\admin\model\GroupRole;
use app\admin\model\RolePermission;
use app\admin\model\Users;
use app\admin\model\Permission;
use app\admin\controller\AdminAuth;
use think\Db;
use think\Validate;
use think\Image;
use think\Request;
class PermissionController extends AdminAuth
{
	//模块基本信息
	private $data = array(
		'module_name' => '节点',
		'module_url'  => '/admin/Permission/',
		'module_slug' => 'Users',
		'upload_path' => UPLOAD_PATH,
		'upload_url'  => '/public/uploads/',
		);

    /**
     * [index 获取节点列表]
     * @return [type] [description]
     */
    public function index()
    {
        $permission_str =  permissionCollection::getAllPermission();
        $permission = permissionCollection::getPermissionByPermissionString($permission_str);
        $this->assign('data',$this->data);
        $this->assign('permission',$permission);
        return $this->fetch();
    }

    /**
     * [create 新增节点数据页面]
     * @return [type] [description]
     */
    public function create()
    {
        $pid = Permission::where('level','=','2')->where('level','=','2')->column('name','id');
    	$this->data['edit_fields'] = array(
			'name'      => array('type' => 'text', 'label'     => '节点名称'),
			'path'      => array('type' => 'text', 'label'     => '节点路径'),
            'type'      => array('type' => 'radio','label'   => '节点类型','default'=> array(0 => '节点', 1 => '选择器')),
			'icon'      => array('type' => 'text', 'label' => '图标'),
			'level'     => array('type' => 'select', 'label'  => '节点等级','default'=> array(3 => '操作方法', 2 => '模块')),
			'pid'       => array('type' => 'select','label'   => '模块', 'default' => $pid),
            'if_menu'   => array('type' => 'radio','label'=> '是否菜单','default'=> array(0 => '否', 1 => '是')),
			'status'    => array('type' => 'radio', 'label'=> '状态','default'=> array(-1 => '删除', 0 => '正常', 1 => '禁用')),
        );

        //默认值设置
        $item['status']    = '正常';
        $item['type']      = '节点';
        $item['if_menu']   = '否';
        $item['level']   = '操作方法';

        $this->assign('item',$item);
        $this->assign('data',$this->data);
        return view();
    }

    /**
     * [add 新增节点数据ACTION，create()页面表单数据提交到这里]
     * @return [type] [description]
     */
    public function add()
    {
        $Permission = new Permission;
        $data = input('post.');

        $rule = [
            //管理员登陆字段验证
            'name|节点名称'   => 'require|min:2',
			'path|节点路径' => 'require',
			'type|节点类型'   => 'require',
			'level|节点等级'   => 'require',
			'if_menu|是否菜单'     => 'require',
            'status|状态'     => 'require',
        ];
        // 数据验证
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return  $this->error($validate->getError());
        }

        $data['create_time'] = time();
        $data['update_time'] = time();


        if ($id = $Permission->validate(true)->insertGetId($data)) {
            return $this->success('添加成功',$this->data['module_url'].'index');
        } else {
            return $this->error($Permission->getError());
        }
    }



    /**
     * [read 读取节点数据]
     * @param  string $id [节点ID]
     * @return [type]     [description]
     */
    public function read($id='')
    {
        $pid = Permission::where('level','=','2')->where('level','=','2')->column('name','id');
        $this->data['edit_fields'] = array(
            'name'      => array('type' => 'text', 'label'     => '节点名称'),
            'path'      => array('type' => 'text', 'label'     => '节点路径'),
            'type'      => array('type' => 'radio','label'   => '节点类型','default'=> array(0 => '节点', 1 => '选择器')),
            'icon'      => array('type' => 'text', 'label' => '图标'),
            'level'     => array('type' => 'select', 'label'  => '节点等级','default'=> array(3 => '操作方法', 2 => '模块')),
            'pid'       => array('type' => 'select','label'   => '模块', 'default' => $pid),
            'if_menu'   => array('type' => 'radio','label'=> '是否菜单','default'=> array(0 => '否', 1 => '是')),
            'status'    => array('type' => 'radio', 'label'=> '状态','default'=> array(-1 => '删除', 0 => '正常', 1 => '禁用')),
        );

        //默认值设置
        $item = Permission::get($id);
        $this->assign('item',$item);
        $this->assign('data',$this->data);
        return view();
    }

    /**
     * [update 更新节点数据，read()提交表单数据到这里]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function update($id)
    {
        $Permission = new Permission;
        $data = input('post.');
        $preview = $Permission->where(array('id'=>$id))->find();

        $rule = [
            //管理员登陆字段验证
            'name|节点名称'   => 'require|min:2',
            'path|节点路径' => 'require',
            'type|节点类型'   => 'require',
            'level|节点等级'   => 'require',
            'if_menu|是否菜单'     => 'require',
            'status|状态'     => 'require',
        ];
        $msg = [];

        // 数据验证
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($data);
        if(!$result){
            return  $this->error($validate->getError());
        }

        $data['id'] = $id;

        if ($Permission->update($data)) {
            return $this->success('节点信息更新成功',$this->data['module_url'].$id);
        } else {
            return $Permission->getError();
        }
    }

    /**
     * [permissionList 权限分配页面]
     * @return [type] [description]
     */
    public function permission_list($group_id=0, $role_id=0)
    {
        //获取所有部门
        $groups = Group::where('status',1)->field('group_name,id')->select();

        //获取所有节点
        $permission_str =  permissionCollection::getAllPermission();
        $permission = permissionCollection::getPermissionByPermissionString($permission_str);

        //查询当前部门角色权限
        $role_permission = '';
        $roles = [];
        if($group_id > 0 && $role_id > 0){
            $roles =  Db::table('tp_group_role')
                ->alias('gr')
                ->where('gr.group_id','=',$group_id)
                ->field('gr.group_id,gr.role_id,r.name')
                ->join('tp_role r','gr.role_id = r.id','LEFT')
                ->select();
            $res = permissionCollection::getUserPermissionByGroupRole($group_id, $role_id);
            $role_permission = $res['permission_id'];
        }

        $this->assign('data',$this->data);
        $this->assign('groups',$groups);
        $this->assign('roles',$roles);
        $this->assign('group_id',$group_id);
        $this->assign('role_id',$role_id);
        $this->assign('permission',$permission);
        $this->assign('role_permission',$role_permission);
        return $this->fetch();
    }

    /**
     * [提交分配数据]
     * @param Request $request
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function permission_add(Request $request){
        $group_id  = $request->param('group_id');
        $role_id   = $request->param('role_id');
        $check_ids = $request->param('check_ids');

        //查询是否存在该部门角色权限
        $exist = RolePermission::where('group_id','=',$group_id)->where('role_id','=',$role_id)->find();

        $data = [];
        if(count($exist) > 0){
            $data['id'] = $exist['id'];
            $data['permission_id'] = $check_ids;
            if (RolePermission::where('id','=',$exist['id'])->update($data)) {
                $return_data['data']   = [];
                $return_data['code']    = '200';
                $return_data['message'] = '操作成功';
                echo json_encode($return_data);exit;
            } else {
                $return_data['data']   = [];
                $return_data['code']    = '4001';
                $return_data['message'] = '操作失败';
                echo json_encode($return_data);exit;
            }
        }else{
            $data['group_id']      = $group_id;
            $data['role_id']       = $role_id;
            $data['permission_id'] = $check_ids;
            $data['create_time'] = time();
            $data['update_time'] = time();
            if(RolePermission::insertGetId($data)){
                $return_data['data']   = [];
                $return_data['code']    = '200';
                $return_data['message'] = '操作成功';
                echo json_encode($return_data);exit;
            } else {
                $return_data['data']   = [];
                $return_data['code']    = '4001';
                $return_data['message'] = '操作失败';
                echo json_encode($return_data);exit;
            }

        }
    }


}